package com.zhkj.framework.config;

import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.google.common.collect.Lists;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Auther: zhangy
 * @Date: 2018/10/12 11:43
 * @Description:druid连接池配置Bean   监控地址：127.0.0.1：8080/druid
 * 操作步骤：
 * 第一步：在DAO层config包下创建DruidConfig配置java文件，采用Bean方式（非xml）
 * 第二步：Application.properties文件中配置Druid属性，同时注销原Spring.DataSource配置
 * 第三步：导入servlet-api.jar到lib中，选中项目-->file-->project structure-->libraries--"➕"
 * 提示一下错误，执行第三步
 * The import javax.servlet cannot be resolved
 * The import javax.servlet.http.HttpServletRequest cannot be resolved
 */
@Configuration
public class DruidConfig {


    //实例化Druid连接池
    @ConfigurationProperties(prefix = "spring.druid")
    @Bean(initMethod = "init",destroyMethod = "close")
    public DruidDataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setProxyFilters(Lists.newArrayList(statFilter()));
        return dataSource;
    }

    //添加Druid过滤器，筛选慢sql
    @Bean
    public Filter statFilter(){
        StatFilter filter = new StatFilter();
        filter.setSlowSqlMillis(1);
        filter.setLogSlowSql(true);
        filter.setMergeSql(true);
        return filter;
    }

    //
    @Bean
    public ServletRegistrationBean servletRegistrationBean(){
        return new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
    }

}
